﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Shapes;

namespace Tetris.Model
{
    public delegate void ElementToCollectionAdded();
    public delegate void ElementFromCollectionDeleted(int index);


    //zgodnie ze sztuka powinienem zrobic dziedziczenie dla kolekcji tetrisowej
    public class CollectionModel<T>: ICollectionModel<T> where T : class
    {
        public CollectionModel()
        {
            this._list = new List<T>();
        }

        #region ICollectionModel imnplementation

        public void Add(T item)
        {
            _list.Add( item );
            this.NotifyElementToCollectionAdded();
        }

        private void NotifyElementToCollectionAdded()
        {
            if (this.ElementToCollectionAdded != null)
            {
                this.ElementToCollectionAdded();
            }
        }

        private void NotifyElementFromCollectionDeleted(int index)
        {
            if( this.ElementFromCollectionDeleted != null)
            {
                this.ElementFromCollectionDeleted(index);
            }
        }

        public T Last()
        {
            return this._list.Last();
        }

        public void Delete(T item)
        {
            this._list.Remove(item);
        }
        
        public void Delete(int index)
        {
            this._list.RemoveAt(index);
            this.NotifyElementFromCollectionDeleted(index);
        }

        public void Delete(Func<T, bool> predicate)
        {
            //znalezc elementy, ktore spelniaja predykat
            var toDelete = (from e in this._list where predicate(e) select e).ToList();
            
            //usunac je
            foreach (var block in toDelete)
            {
                this._list.Remove(block);
            }
        }

        public bool Contains(Func<T, bool> predicate)
        {
            return this._list.FirstOrDefault( predicate ) != null ;
        }

        #endregion

        #region public fields

        public event ElementToCollectionAdded ElementToCollectionAdded;
        public event ElementFromCollectionDeleted ElementFromCollectionDeleted;


        #endregion

        #region private fields 

        private readonly IList<T> _list;

        #endregion

        #region implementation of IEnumerable

        public IEnumerator<T> GetEnumerator()
        {
            return this._list.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this._list.GetEnumerator();
        }

        #endregion

    }
}
